package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmChannelDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmChannelService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2023/3/16 10:51
 * @Version 1.0
 */
@Service
@RequiredArgsConstructor
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {
    private static final String CHANNEL_WORDS_KEY = "channelWords";
    private final WmNewsMapper wmNewsMapper;
    private final RedisTemplate<String, Object> redisTemplate;


    @Override
    public ResponseResult findAll() {
        Object o = redisTemplate.opsForValue().get(CHANNEL_WORDS_KEY);
        if (o != null) {
            return ResponseResult.okResult(o);
        }
        List<WmChannel> list = list();
        redisTemplate.opsForValue().set(CHANNEL_WORDS_KEY, list);
        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult delById(Integer id) {
        WmChannel wmChannel = getBaseMapper().selectById(id);
        if (wmChannel == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "频道不存在");
        }
        if (wmChannel.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FORBIDDEN, "禁用的频道才能删除");
        }
        getBaseMapper().deleteById(id);

        Object o = redisTemplate.opsForValue().get(CHANNEL_WORDS_KEY);
        List<WmChannel> channelWords = (List<WmChannel>) o;
        if (channelWords != null) {
            //过滤掉删除的频道
            channelWords.removeIf(item -> Objects.equals(item.getName(), wmChannel.getName()));
            //更新value
            redisTemplate.opsForValue().getAndSet(CHANNEL_WORDS_KEY, channelWords);
        }
        return ResponseResult.okResult(null);
    }

    @Override
    public ResponseResult listPage(WmChannelDto dto) {
        dto.checkParam();
        Page<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmChannel> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(dto.getName()), WmChannel::getName, dto.getName());
        wrapper.orderByDesc(WmChannel::getCreatedTime);
        getBaseMapper().selectPage(page, wrapper);
        return ResponseResult.okResult(page.getRecords());
    }

    @Override
    public ResponseResult saveChannel(WmChannel wmChannel) {
        if (wmChannel == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "参数不能为空");
        }
        List<WmChannel> wmChannels = getBaseMapper().selectList(new LambdaQueryWrapper<WmChannel>().eq(WmChannel::getName, wmChannel.getName()));
        if (!CollectionUtils.isEmpty(wmChannels)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "频道名称不能重复");
        }
        wmChannel.setCreatedTime(new Date());
        wmChannel.setIsDefault(true);
        getBaseMapper().insert(wmChannel);

//         更新 Redis
        Object o = redisTemplate.opsForValue().get(CHANNEL_WORDS_KEY);
        List<WmChannel> channelWords = (List<WmChannel>) o;
        if (channelWords != null) {
            channelWords.add(wmChannel);
            redisTemplate.opsForValue().set(CHANNEL_WORDS_KEY, channelWords);
        } else {
            redisTemplate.opsForValue().set(CHANNEL_WORDS_KEY, Collections.singletonList(wmChannel));
        }

        return ResponseResult.okResult(null);
    }

    @Override
    public ResponseResult updateChannel(WmChannel wmChannel) {
        if (wmChannel == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "参数不能为空");
        }
        String oldName = wmChannel.getName();
        if (wmChannel.getStatus()) {
            getBaseMapper().updateById(wmChannel);
            return ResponseResult.okResult(null);
        }

        List<WmNews> wmNews = wmNewsMapper.selectList(new LambdaQueryWrapper<WmNews>().eq(WmNews::getChannelId, wmChannel.getId()));
        if (!CollectionUtils.isEmpty(wmNews)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "频道下存在新闻，不能修改");
        }


        getBaseMapper().updateById(wmChannel);
        Object o = redisTemplate.opsForValue().get(CHANNEL_WORDS_KEY);
        List<WmChannel> channelWords = (List<WmChannel>) o;
        if (channelWords != null) {
         channelWords.removeIf(item -> Objects.equals(item.getName(), oldName));
         channelWords.add(wmChannel);
         redisTemplate.opsForValue().set(CHANNEL_WORDS_KEY, channelWords);
        }
        return ResponseResult.okResult(null);
    }
}
